package com.zenchn.schedule;

import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;

import java.util.Date;
import java.util.concurrent.ScheduledFuture;


/**
 * 定时任务
 *
 * @author panbingqi
 * @date 2021-06-01
 */
public class TaskScheduler {

    private ThreadPoolTaskScheduler threadPoolTaskScheduler;


    private ScheduledFuture<?> scheduledFuture;

    /**时间表达式**/
    private String cron = "";

    /**间隔时间**/
    private Long fixedDelay;

    /**定时任务工作体**/
    private Runnable runnable;

    public TaskScheduler(Runnable runnable, String cron, ThreadPoolTaskScheduler threadPoolTaskScheduler) {
        super();
        this.runnable = runnable;
        this.cron = cron;
        this.threadPoolTaskScheduler = threadPoolTaskScheduler;
    }

    public TaskScheduler(Runnable runnable, Long fixedDelay, ThreadPoolTaskScheduler threadPoolTaskScheduler) {
        super();
        this.runnable = runnable;
        this.fixedDelay = fixedDelay;
        this.threadPoolTaskScheduler = threadPoolTaskScheduler;
    }

    public Runnable getRunnable() {
        return runnable;
    }

    public String getCron() {
        return cron;
    }

    public Long getFixedDelay() {
        return fixedDelay;
    }

    public ScheduledFuture<?> getScheduledFuture() {
        return scheduledFuture;
    }

    /**
     * 停止定时任务
     */
    public void stop() {
        if (scheduledFuture != null) {
            scheduledFuture.cancel(true);
        }
    }

    /**
     * 设置时间表达式
     *
     * @param cron
     */
    public void setCron(String cron) {
        this.cron = cron;
        stop();
        scheduledFuture = threadPoolTaskScheduler.schedule(runnable, new CronTrigger(cron));
    }

    /**
     * 设置间隔时间
     *
     * @param fixedDelay
     */
    public void setFixedDelay(Long fixedDelay) {
        this.fixedDelay = fixedDelay;
        stop();
        scheduledFuture = threadPoolTaskScheduler.scheduleWithFixedDelay(runnable,new Date(),fixedDelay);
    }

    /**
     * 开启任务
     */
    public void start(String cron,Long fixedDelay){
        if (null!=fixedDelay){
            this.setFixedDelay(fixedDelay);
        }
        if (null!=cron && !"".equals(cron)){
            this.setCron(cron);
        }
    }
}